// src/background/index.ts - Background Service Worker
// Chrome Extension Manifest V3 Background Script
// 三入口汇聚架构：工具栏图标 + Alt+S快捷键 + 悬浮按钮

import { toggleSidePanel, cleanupTabState, resetTabState, getSidebarStatus } from './toggle';

console.log('SideX Background Service Worker started');

// 侧边栏状态跟踪
const sidePanelStates = new Map<number, boolean>(); // tabId -> isOpen

// Install event
chrome.runtime.onInstalled.addListener((details) => {
  console.log('Extension installed:', details);

  // Create context menu
  chrome.contextMenus.create({
    id: 'sidex-open',
    title: 'Toggle SideX Panel',
    contexts: ['page', 'selection'],
  });
});

// =============================================================================
// 入口1: 工具栏图标点击
// =============================================================================
chrome.action.onClicked.addListener((tab) => {
  console.log('[Entry 1] Toolbar icon clicked');
  if (tab.id) {
    toggleSidePanel(tab.id);
  }
});

// =============================================================================
// 入口2: Alt+S 快捷键
// =============================================================================
chrome.commands.onCommand.addListener((command, tab) => {
  console.log('[Entry 2] Command triggered:', command);
  if (command === '_execute_action' && tab?.id) {
    toggleSidePanel(tab.id);
  }
});

// =============================================================================
// 入口3: 悬浮按钮 - 同步链处理
// =============================================================================
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log('Received message:', message);

  // 支持新旧消息格式
  const action = message.action || message.type || message.cmd;
  const data = message.data || message;

  switch (action) {
    case 'TOGGLE':
    case 'SIDEX_TOGGLE':
    case 'TOGGLE_SIDE_PANEL':
      console.log('[Entry 3] Float button toggle request');
      if (sender.tab?.id) {
        // 关键：同步调用，保持用户手势链
        toggleSidePanel(sender.tab.id);
        sendResponse({ success: true });
      } else {
        sendResponse({ success: false, error: 'No tab ID available' });
      }
      break;

    case 'GET_TAB_INFO':
      if (sender.tab) {
        sendResponse({
          tabId: sender.tab.id,
          url: sender.tab.url,
          title: sender.tab.title,
        });
      }
      break;

    case 'PAGE_LOADED':
      console.log('Page loaded on tab:', sender.tab?.id);
      if (sender.tab?.id && data) {
        chrome.storage.local.set({
          [`pageData_${sender.tab.id}`]: data
        });
      }
      sendResponse({ received: true });
      break;

    case 'TEXT_SELECTED':
      console.log('Text selected:', data.text || message.text);
      chrome.storage.local.set({
        lastSelectedText: {
          text: data.text || message.text,
          url: data.url || message.url,
          title: data.title || message.title,
          timestamp: Date.now()
        }
      });
      sendResponse({ received: true });
      break;

    case 'ANALYZE_PAGE':
      // 转发给内容脚本进行页面分析
      if (sender.tab?.id) {
        chrome.tabs.sendMessage(sender.tab.id, {
          action: 'ANALYZE_PAGE',
          data: data
        }).then(response => {
          sendResponse(response);
        }).catch(error => {
          console.error('Error forwarding analyze message:', error);
          sendResponse({ success: false, error: error.message });
        });
        return true; // 保持消息通道开放用于异步响应
      }
      break;

    case 'UPDATE_SIDE_PANEL_STATE':
      // 外部状态更新通知
      if (sender.tab?.id) {
        const isOpen = data.isOpen || message.isOpen;
        if (typeof isOpen === 'boolean') {
          // 这里不直接设置状态，因为状态应该由toggle函数管理
          console.log(`[State Update] External state notification: ${isOpen}`);
        }
      }
      sendResponse({ success: true });
      break;

    default:
      console.log('Unknown message type:', action);
      sendResponse({ error: 'Unknown message type' });
  }

  return true; // Keep message channel open for async response
});

// Context menu click handler
chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === 'sidex-open' && tab?.id) {
    toggleSidePanel(tab.id);
  }
});

// =============================================================================
// 生命周期管理
// =============================================================================

// 监听标签页关闭，清理状态
chrome.tabs.onRemoved.addListener((tabId) => {
  cleanupTabState(tabId);
});

// 监听标签页更新，重置状态
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === 'loading') {
    // 页面开始加载时重置侧边栏状态
    resetTabState(tabId);
  }

  if (changeInfo.status === 'complete' && tab.url) {
    console.log('Tab updated:', tab.url);
  }
});

// Storage change listener
chrome.storage.onChanged.addListener((changes, areaName) => {
  console.log('Storage changed:', changes, areaName);
});

// Keep service worker alive
setInterval(() => {
  console.log('Service worker heartbeat');
}, 20000);